package com.demo.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.R;
import com.demo.item.SongItem;

import java.util.List;

/**
 * Created by VietBui on 11/26/13.
 */
public class AdapterSong extends ArrayAdapter<SongItem> {
    private LayoutInflater inflater;

    public AdapterSong(Context context, List<SongItem> objects) {
        super(context, -1, objects);
        inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        SongItem songItem = getItem(position);
        ViewHolder viewHolder;

        if(null == convertView){
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_song,null);
            viewHolder.txtTitleSong = (TextView) convertView.findViewById(R.id.txt_title_song);
            viewHolder.btnDelete = (Button) convertView.findViewById(R.id.btn_delete_item);
            Log.e("Adapter","NULL Position = " + position);
            convertView.setTag(viewHolder);
        }else{
            //Reset data truoc khi fill data moi vao
            viewHolder = (ViewHolder) convertView.getTag();
            Log.e("Adapter","!NULL Position = " + position + " | last value = " + viewHolder.txtTitleSong.getText());
            viewHolder.txtTitleSong.setText("");
        }
        viewHolder.btnDelete.setOnClickListener(new OnDeleteItem(position));
        viewHolder.txtTitleSong.setText(songItem.getTitle());
        return convertView;
    }

    private class ViewHolder{
        TextView txtTitleSong;
        Button btnDelete;
    }

    private class OnDeleteItem implements View.OnClickListener{

        private final int position;

        OnDeleteItem(int position){
            this.position = position;
        }

        @Override
        public void onClick(View view) {
            Toast.makeText(getContext(),"Delete at = " + position,Toast.LENGTH_SHORT).show();
            SongItem songItem = AdapterSong.this.getItem(position);
            AdapterSong.this.remove(songItem);
            AdapterSong.this.notifyDataSetChanged();
        }
    }
}

